﻿using System;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
using Medianamik.Core;
using Medianamik.Core.Configuration;
using Medianamik.Core.Sugar;
using Medianamik.Globalization;
using Telerik.Web.UI;

namespace Medianamik.UI.Controls
{
    /// <summary>
    /// Contrôle d'édition HTML riche
    /// </summary>
    public class Editor : BaseEditor
    {
        public Editor(MedianamikConfigSection config)
            : base(config)
        {

        }

        public Editor()
        {

        }

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {
            Controls.Add(editor);
            editor.ID = ControlToValidateId;

            if (pUseDataSource)
            {
                editor.Content = (DataSource == null) ? String.Empty : DataSource.ToString();
                editor.CssClass = "Editor";

                editor.Width = ControlInfo.Width.HasValue ? ControlInfo.Width.Value : WIDTH;

                editor.Height = ControlInfo.Height.HasValue ? ControlInfo.Height.Value : HEIGHT;

                editor.Skin = Skins.DEFAULT_SKIN;
                editor.EnableEmbeddedSkins = Skins.DEFAULT_USE_EMBEDDED_SKIN;
                editor.EditModes = EditModes.Design ^ EditModes.Html;
                SetEditorToolbarMode(editor);

                //Content Filters
                editor.NewLineBr = false;

                editor.ContentFilters = EditorFilters.DefaultFilters;
                //editor.ContentFilters &= ~EditorFilters.FixEnclosingP;
                //editor.ContentFilters &= ~EditorFilters.IECleanAnchors;
                editor.ContentFilters &= ~EditorFilters.MakeUrlsAbsolute;
                //editor.ContentFilters &= ~EditorFilters.ConvertCharactersToEntities;

                editor.OnClientPasteHtml = "OnClientPasteHtml";

                string editorXml = GetEditorXml();
                var editorXmlDoc = new XmlDocument();
                editorXmlDoc.LoadXml(editorXml);

                if (CurrentSite == null)
                {
                    #region Retirer le TemplateManager

                    var xmlReader = new XmlNodeReader(editorXmlDoc);
                    XDocument xDoc = XDocument.Load(xmlReader);

                    var toolBar = from bar in xDoc.Descendants("tools")
                                  where (string)bar.Attribute("name") == "InsertToolbar"
                                  select bar;

                    var templateMan = from tool in toolBar.Descendants("tool")
                                      where (string)tool.Attribute("name") == "TemplateManager"
                                      select tool;

                    templateMan.Remove();


                    editorXmlDoc.Load(xDoc.CreateReader());

                    #endregion

                    editor.LoadToolsFile(editorXmlDoc);
                    editor.CssFiles.Clear();
                    editor.CssClasses.Clear();

                    //Pour les gabarits
                    if (CurrentType != null && CurrentType.ID == MedianamikTypes.MedianamikTemplate)
                    {
                        Guid? webSiteId = null;

                        if (CurrentNode == null)
                            StringHelper.IsGuid(Page.Request.QueryString[QueryStringParamNames.WebSiteId],
                                ref webSiteId);
                        else
                            webSiteId = CurrentNode.DefaultInstance[MedianamikProperties.MedianamikTemplateWebSiteId].GetValue<Guid?>();

                        if (webSiteId.HasValue)
                        {
                            var site = ConfigManager.Get<WebSite>(webSiteId.Value);
                            if (site != null)
                            {
                                _cssFilePath = String.IsNullOrEmpty(site.CSSFilePath)
                                               ? Config.DefaultEditorCSSFilePath
                                               : site.CSSFilePath;

                                editor.CssFiles.Add(_cssFilePath);
                            }
                        }
                    }
                    else
                    {
                        editor.CssFiles.Add(Config.DefaultEditorCSSFilePath);
                    }
                }
                else
                {
                    editor.LoadToolsFile(editorXmlDoc);

                    editor.CssFiles.Clear();
                    editor.CssClasses.Clear();

                    _cssFilePath = String.IsNullOrEmpty(CurrentSite.CSSFilePath)
                                   ? Config.DefaultEditorCSSFilePath
                                   : CurrentSite.CSSFilePath;

                    editor.CssFiles.Add(_cssFilePath);

                    var medianamikTemplate = new DialogDefinition(typeof(TemplatePicker), new DialogParameters());
                    medianamikTemplate.Parameters.Add("website", CurrentSite.ID.ToString());
                    medianamikTemplate.Parameters.Add("css", _cssFilePath);
                    medianamikTemplate.Modal = true;
                    medianamikTemplate.Title = Translator.Translate("Medianamik_ContentManagement", "MedianamikTemplateWindowTitle");
                    medianamikTemplate.VisibleTitlebar = true;
                    medianamikTemplate.VisibleStatusbar = false;
                    medianamikTemplate.Width = Unit.Pixel(625);
                    medianamikTemplate.Height = Unit.Pixel(450);
                    medianamikTemplate.ReloadOnShow = true;
                    medianamikTemplate.Behaviors = WindowBehaviors.Close | WindowBehaviors.Move | WindowBehaviors.Resize;
                    editor.AddDialogDefinition("MedianamikTemplate", medianamikTemplate);
                }

                ConfigureDialogs();

                editor.DialogsCssFile = "/Medianamik/includes/medianamik-window.css?v=" +
                    Utility.GetFileVersion();

                //Provide an option for clearing the style
                AddParagraphs("Controls.Editor.Paragraphs.xml");
            }
        }

        protected override string GetEditorXml()
        {
            return Resources.GetResourceText("Controls.Editor.EditorFull.xml",
                Assembly.GetExecutingAssembly());
        }

        protected virtual void ConfigureDialogs()
        {
            SetDialogPaths(editor.ImageManager, (CurrentSite == null || String.IsNullOrEmpty(CurrentSite.EditorImageFilesPath)) ?
                Config.EditorImageFilesPath : CurrentSite.EditorImageFilesPath);

            SetDialogPaths(editor.DocumentManager, (CurrentSite == null || String.IsNullOrEmpty(CurrentSite.EditorDocumentFilesPath)) ?
                Config.EditorDocumentFilesPath : CurrentSite.EditorDocumentFilesPath);

            SetDialogPaths(editor.FlashManager, (CurrentSite == null || String.IsNullOrEmpty(CurrentSite.EditorFlashFilesPath)) ?
                Config.EditorFlashFilesPath : CurrentSite.EditorFlashFilesPath);

            SetDialogPaths(editor.MediaManager, (CurrentSite == null || String.IsNullOrEmpty(CurrentSite.EditorMediaFilesPath)) ?
                Config.EditorMediaFilesPath : CurrentSite.EditorMediaFilesPath);

            SetDialogSearchPatterns(editor.ImageManager, Config.EditorImageFilesExtension, "*.jpg", "*.jpeg", "*.gif", "*.png");
            SetDialogSearchPatterns(editor.DocumentManager, Config.EditorDocumentFilesExtension, "*.doc", "*.txt", "*.docx", "*.xls", "*.xlsx", "*.pdf");
            SetDialogSearchPatterns(editor.FlashManager, Config.EditorFlashFilesExtension, "*.flv", "*.swf");
            SetDialogSearchPatterns(editor.MediaManager, Config.EditorMediaFilesExtension, "*.wma", "*.wmv", "*.avi",
                                    "*.wav", "*.mpeg", "*.mpg", "*.mpe", "*.mp3", "*.m3u", "*.mid", "*.midi", "*.snd",
                                    "*.mkv");
        }
    }
}